
(function($, win, doc){
	
	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	var sqlMirror = (function (){

		var aesPwd = 'Xxeicq3gknHJEsZR';
		var editor = null;
		var script = null;
		
		function generateTemplate(){
			
			var scriptTxt = ['SELECT ID, NAME, CODE'];
			scriptTxt.push('FROM ORG_MEMBER');
			scriptTxt.push('WHERE CODE LIKE :code');
			scriptTxt.push('');
			
			return scriptTxt.join('\r\n');
		}
		
		
		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
						
						$.setEleValue('#script_content', script = generateTemplate());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-sql',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = (_script ? $.aes_decrypt(_script, aesPwd) : generateTemplate());
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	var app = new Vue({
		el: '#app',
		data: {
			basic:{
				code: null
			},
			style:{
				selectedIndex: 'first'
			},
			formData:{
				main: {
					listData:[{
						id: null,
						name: '测试测试测试测试测试测试测试测试测试测试',
						code: 'DAPI_20211112160904562571',
						url: '',
						description: '... ...',
						ts: '2021-01-01 00:00:00'
					}]
				},
				edit: {
					fields:{
						id: null,
						type: 'sql',
						name: '',
						code: '',
						url: '',
						ds: null,
						description: ''
					},
					options: {
						ds:[
							{name: 'A8', mark: '---'}
						]
					},
					rules: {
					  name: [
						  { required: true, message: '请输入名称', trigger: 'blur' },
						  { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
					  ],
					  code: [
						  { required: true, message: '请输入编号', trigger: 'blur' },
						  { 
							  validator: function(rule, value, callback){
								  
								  if(/^[A-Z][A-Z_0-9]{5,}$/g.test(value)){
									  
									  callback();
									  
								  }else{
									  callback(new Error('编号式格式错误！必须由6位以大写字母、数字（或下划线）组成，且首位字母。'));
								  }
							  }, 
							  trigger: 'blur' 
						  }
					  ]
					}
				}
			}
		},
		methods:{
			init: function(){
				
				this.loadAPIListData();	
				
				this.loadDSOptions();
				
			},
			loadAPIListData: function(){
				
				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/rest/snail/setting'),
					header: {'Accept': 'application/json'},
					onsuccess: function(result, status, xhr){
						
						if(200 == result.code){
							
							var apiList = [];
							
							for(var i=0,len=result.data.length; i<len; i++){
								
								if('sql' == result.data[i].type){
									
									apiList.push(result.data[i]);
								}
							}

							_this.formData.main.listData = apiList;
							
						}else{
							_this.$alert(result.message, '异常');
						}

					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			loadDSOptions: function(){
				
				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/rest/snail/setting/ds_list'),
					header: {'Accept': 'application/json'},
					onsuccess: function(result, status, xhr){
						
						if(200 == result.code){
							
							_this.formData.edit.options.ds = result.data;
							
						}else{
							_this.$alert(('加载数据源列表失败！ERROR: ' + result.message), '异常');
						}
					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			loadScriptInfo: function(){
				
				if($.isBlank(this.formData.edit.fields.code)){
					return ;
				}
				
				var _this = this;
				
				$.http.get({
					url: (appBasePath + '/rest/snail/setting/sql/' + this.formData.edit.fields.code),
					header: {'Accept': 'text/plain'},
					onsuccess: function(result, status, xhr){
						
						!$.isBlank(result) && sqlMirror.setValue(result);
					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			onTabsChange: function(tab, event){
				
				if('first' == tab.name){
					
					this.loadAPIListData();
					
				}else if('second' == tab.name){
					
					sqlMirror.init();
					
					this.loadScriptInfo();
				}
			},
			onCodeChange: function(value){
				
				if($.isBlank(value)){
					return;
				}
				
				this.formData.edit.fields.url = 'http://127.0.0.1:80/seeyon/rest/snail/db/' + value;
			},
			onAdd: function(){
				this.openEditTabs('NEW');
			},
			onEdit: function(code){
				this.openEditTabs(code);
			},
			onDelete: function(code){
				
				var _this = this;
				
				$.http.delete({
					url: (appBasePath + '/rest/snail/setting/sql/' + code + '/delete'),
					header: {'Accept': 'application/json'},
					onsuccess: function(result, status, xhr){
						
						_this.$alert(result.message, '信息');

						_this.loadAPIListData();
					},
					onerror: function(responseText, status, xhr){
						console.log(responseText);
					}
				});
			},
			onSave: function(){
				
				var _this = this;
				
				this.$refs.editFormData.validate(function(valid){
					
					if(valid){

						Snail.http.post({
							url: '/seeyon/rest/snail/setting/deploy',
							header:{'Content-Type': 'application/json', 'Accept': 'application/json'},
							data: _this.getFormData(),
							onsuccess: function(data, status, xhr){
								
								if(200 == data.code){
									
									alert("部署成功");
									
								}else{
									_this.$alert(data.message, '异常');
								}
							},
							onerror: function(responseText, status, xhr){
								_this.$alert(responseText, '异常');
							},
							oncomplete: function(responseText, status, xhr){
								;
							}
						});
						
					}else{
						_this.$alert('数据校验不通过！', '异常');
					}
				});

			},
			onTest: function(){
				
				win.parent.Snail.appLayout.openTestTabs(this.formData.edit.fields.code, this.formData.edit.fields.type);
			},
			onRelease: function(){

				var _this = this;
				
				$.http.post({
					url: (appBasePath + '/rest/snail/setting/release'),
					header:{'Content-Type': 'application/json', 'Accept': 'application/json'},
					data: {
						code: this.formData.edit.fields.code,
						name: this.formData.edit.fields.name,
						type: 'sql'
					},
					onsuccess: function(data, status, xhr){
						
						if(200 == data.code){

							_this.$alert("发布成功", '信息');
														
						}else{
							_this.$alert(data.message, '异常');
						}
					},
					onerror: function(responseText, status, xhr){
						_this.$alert(responseText, '异常');
					},
					oncomplete: function(responseText, status, xhr){
						;
					}
				});
				
			},
			getFormData: function(){
				
				var data = $.extend({script: null}, this.formData.edit.fields, true);
				
				data.script = sqlMirror.getValue();
				
				return data;
			},
			setFormData: function(data){
				
				sqlMirror.setValue(data.script);
				
				$.extend(this.formData.edit.fields, data, true);
			},
			openEditTabs: function(code){
				
				if('NEW' == code){
					
					this.setFormData({
						id: null,
						type: 'sql',
						name: '',
						code: '',
						url: '',
						script: null,
						ds: null,
						description: ''
					});
					
				}else if(this.formData.main.listData && this.formData.main.listData.length){
					
					for(var i=0,len=this.formData.main.listData.length; i<len; i++){
						
						if(code == this.formData.main.listData[i].code){
							
							this.setFormData(this.formData.main.listData[i]);
							
							break;
						}
					}
				}
								
				$.onEvent('#tab-second', 'click');
			}
		},
		created: function(){
			this.init();
		}
	});
	

})(Snail, window, document);